<template>
  <view
    v-if="showModal"
    class="fixed top-0 left-0 w-full h-full bg-[rgba(0,0,0,0.5)] flex items-end"
    @click="onClose"
  >
    <view class="w-full bg-white rounded-t-[20rpx] px-12 py-3 z-2" @click.stop>
      <button
        class="w-avatar w-[160rpx] h-[160rpx] m-auto my-5 rounded-full mt-6rounded-full !p-0 border-red line-height-[160rpx] after:border-none flex justify-center items-center"
        open-type="chooseAvatar"
        @chooseavatar="onChooseAvatar"
      >
        <image v-if="userInfo.avatar" :src="userInfo.avatar" mode="aspectFill" class="e-image" />
        <image
          v-else
          src="https://qncdn.mopic.mozigu.net/work/143/24/4f2b263d7a6140f2/person.png"
          mode="aspectFill"
          class="w-[164rpx] h-[164rpx]"
        />
      </button>
      <input
        type="nickname"
        v-model="userInfo.nickname"
        class="e-input"
        placeholder="请输入昵称"
        @input="onInput"
        @blur="onInput"
      />
      <button
        class="w-full my-6 bg-[#69C46A] outline-none !border-none text-white fw-bold rounded-full after:border-none"
        @click="onSubmit"
      >
        确定
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store'

const userStore = useUserStore()
interface userInfoType {
  avatar: string
  nickname: string
}

const showModal = ref(false)
const userInfo = reactive<userInfoType>({
  avatar: '',
  nickname: '',
})

const emit = defineEmits(['submit', 'close'])
// 授权头像
function onChooseAvatar(evt) {
  userInfo.avatar = evt.detail.avatarUrl
}

function onInput(evt) {
  userInfo.nickname = evt.detail.value
}
// 确定
function onSubmit() {
  if (!userInfo.avatar) {
    uni.showToast({
      title: '请选择头像',
      icon: 'none',
    })
    return
  }
  if (!userInfo.nickname) {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none',
    })
    return
  }
  emit('submit', userInfo)
  onClose()
}

defineExpose({ show })

function show() {
  showModal.value = true
}

function onClose() {
  showModal.value = false
}

onMounted(() => {
  userInfo.avatar = userStore.userInfo.headimgurl
  userInfo.nickname = userStore.userInfo.nickname
})
</script>

<style scoped lang="scss">
.w-avatar {
  overflow: hidden;
  box-sizing: border-box;
  box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
  background: #dee3e8;
  text-align: center;
  color: #666;
  border: 4rpx solid #fff;

  &::after {
    border: none;
  }

  .e-image {
    width: 100%;
    height: 100%;
    border-radius: inherit;
  }
}
.e-input {
  border: 1px solid gray;
  padding: 0 20rpx;
  box-sizing: border-box;
  height: 3em;
  line-height: 3em;
  color: #333;
  border-radius: 120rpx;
}
</style>
